package com.tradesolver;

import java.io.IOException;
import java.util.TreeMap;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class CsvServlet extends HttpServlet {
  Logger logger = Logger.getLogger(CsvServlet.class.getName());

  CsvService service = new CsvService();

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    String csv = getCsv(req.getRequestURI()); // /SMC20110330.csv
    resp.setContentType("text/plain");
    resp.getWriter().println("Date,Close\n");
    resp.getWriter().println(csv);
  }

  private String getCsv(String uri) {
    StringBuilder sb = new StringBuilder();
    String query = uri.substring(1, uri.indexOf('.'));
    logger.info("query=" + query);

    String ticker = query.substring(0, query.indexOf('-')).toUpperCase();

    TreeMap<String, TreeMap<String, Quote>> quotesMap = service.getQuotes(new String[] { ticker });
    TreeMap<String, Quote> quotes = quotesMap.get(ticker);

    logger.info("Constructing csv string");
    String fromDate = "20000101";
    for (String date : quotes.tailMap(fromDate).keySet()) {
      Quote quote = quotes.get(date);
      sb.append(date).append(",").append(quote.close).append("\n");
    }
    logger.info("Done Constructing csv string");
    return sb.toString();
  }
}
